import { Component, OnInit, ViewChild } from '@angular/core';

import { DataTablesComponent, DataTablesComponentConfig } from 'app/theme/components/dataTables';
import { CertSearchForm } from './cert-search-form.class';
import { ModalDirective } from "ng2-bootstrap";
import { CertSearchInfo } from "./certificate-search-info.class";
import { CertificateSearchService } from "./certificate-search.service";
@Component({
  selector: 'cert-search-page',
  templateUrl: 'cert-search-page.component.html',
  styleUrls: ['cert-search-page.component.scss'],
  providers: [CertificateSearchService]
})
export class CertSearchPageComponent implements OnInit {

  @ViewChild('applyModal') applyModal: ModalDirective;
  @ViewChild(DataTablesComponent) private certHistoryTable: DataTablesComponent;

  private _certSearchUrl: string = '/water/certificate/selectCertifi';
  private certInfoUrl: string = '/water/certificate/showCerertificate';

  private certSearchForm: CertSearchForm = new CertSearchForm();
  private selectedRowData: any = {};
  private selectedData: CertSearchInfo = new CertSearchInfo();

  private disableViewBtn = true;

  private _errorMsg: string;
  private errorShow = false;
  private dataTableConfig: DataTablesComponentConfig = new DataTablesComponentConfig();


  constructor(private _service: CertificateSearchService) {
  }

  ngOnInit() {
    this.dataTableConfig.ajaxUrl = this._certSearchUrl;
    this.dataTableConfig.columnsDef = [
      {name: '证书编号', id: 'serialno'},
      {name: '证书类别', id: 'type'},
      {name: '姓名', id: 'name'},
      {name: '性别', id: 'sex'},
      {name: '出生日期', id: 'birthday'},
      {name: '企业名称', id: 'companyname'},
      {name: '发证日期', id: 'issuedate'},
      {name: '有效时间', id: 'availabletime'},
      {name: '证书是否有效', id: 'available'}
    ];
    this.dataTableConfig.selectable = 'single';
  }

  search() {
    this.certHistoryTable.draw();
  }

  private toggleView(): void {
    let ids = this.selectedRowData.ids;
    this.loadCertInfo(ids);
  }

  handleError(e:any){
    if(e.type == 'error'){
      this.errorShow = true;
    }
  }

  private loadCertInfo(ids: string) {
    this.selectedData = new CertSearchInfo();
    this._service.loadCertInfo(this.certInfoUrl, ids)
      .then(res => {
        if (res.status === 'success') {
          this.selectedData = res.data;
          this.applyModal.show();
        } else {
          this._errorMsg = res.data ? res.data : '网络错误';
        }
      }, error => {
        this._errorMsg = error;
      });
  }

  onHideModal(): void {
    jQuery(".modal-backdrop").remove();
  }

  tableRowSelect(rowData: any[]) {
    if (rowData.length === 1) {
      this.selectedRowData = rowData[0];
      this.disableViewBtn = false;
    } else {
      this.disableViewBtn = true;
    }
  }
}
